package com.bridgeintelligent.tag.webserver.dim.mgmt.service.export.excel;

import com.bridgeintelligent.tag.webserver.dim.mgmt.api.DimCatalog;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.export.DimAggData;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author JackCheung
 * @date 2020/7/15 8:23 PM.
 * description:
 */
public interface IDimExcelService {

    String FILE_TMP_FULL_NAME = "标签模型TMP.xlsx";
    String FILE_NAME = "标签模型";
    String DIM_UPDATE = "1", DIM_INSERT = "0", ITEM_NAME = "itemName", ITEM_NO = "itemNo", TYPE = "type";

    /**
     * 将list转换为key为dimId的map
     *
     * @param excelList List<DimAggData>
     * @return key—> dimId value->List<DimAggData>
     */
    default Map<String, List<DimAggData>> createAggMapInMap(List<DimAggData> excelList, Map<String, DimCatalog> dimCatalogMap) {
        return excelList.stream()
                        .peek(dimAggData -> {
                            String catalogId = Optional.ofNullable(dimCatalogMap.get(dimAggData.getCatalogId()))
                                                       .map(DimCatalog::getParentId)
                                                       .orElse(dimAggData.getCatalogId());
                            dimAggData.setFirstCatalog(Optional.ofNullable(dimCatalogMap.get(catalogId))
                                                               .map(DimCatalog::getName)
                                                               .orElse(catalogId));
                        })
                        .collect(Collectors.groupingBy(DimAggData::getDimId));
    }

    /**
     * 将list转换为key为dimId的map
     *
     * @param excelList List<DimAggData>
     * @return key—> dimId value->List<DimAggData>
     */
    default Map<String, List<DimAggData>> createAggMap(List<DimAggData> excelList) {
        return excelList.stream()
                        .
                                collect(Collectors.groupingBy(DimAggData::getDimId));
    }

    /**
     * 获取实体字段名及值
     *
     * @param dimAggData dimAggData
     * @return 字段名及值
     * @throws IllegalAccessException IllegalAccessException
     */
    default Map<String, String> fetchField(DimAggData dimAggData) throws IllegalAccessException {
        Class<?> target = dimAggData.getClass();
        Map<String, String> result = new HashMap<>(16);
        Field[] fields = target.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            Object value = field.get(dimAggData);
            result.put(field.getName(), String.valueOf(value));
        }
        return result;
    }
}
